//
//  XRmenuCoreData.m
//  XRmenu
//
//  Created by Gao Yan on 11-11-23.
//  Copyright 2011年 foxhis. All rights reserved.
//

#import "XRmenuCoreData.h"
#import "XRmenu_HDAppDelegate.h"

@implementation XRmenuCoreData
#pragma mark -
#pragma mark XRmenu查询数据库基本操作
//获取推荐菜品对象
+(NSMutableArray*) getAllCommendPlu{
    NSString *condition=[NSString stringWithFormat:@"ppRecommended=1"];
    return [self searchObjectsInContext:@"PluPlu" Predicate:[NSPredicate predicateWithFormat:condition] SortKey:@"ppCode" SortAscending:YES];    
}
//获取所有大类对象
+(NSMutableArray*) getAllPluMenu{
    NSString *condition=[NSString stringWithFormat:@"pmStatus=1"];
    return [self searchObjectsInContext:@"PluMenu" Predicate:[NSPredicate predicateWithFormat:condition] SortKey:@"pmCode" SortAscending:YES];
}
//获取所有已点菜品对象
+(NSMutableArray*) getAllDishOrder{
	return [self searchObjectsInContext:@"DishOrder" Predicate:nil SortKey:@"ddOrderTime" SortAscending:YES];
}
//获取所有桌号对象
+(NSMutableArray*) getAllPluTable{
	return [self searchObjectsInContext:@"PluTable" Predicate:nil SortKey:@"ptTableNo" SortAscending:YES];
}
//获取所有菜品对象(下载时查询图片名)
+(NSMutableArray*) getAllPluPlu{
    return [self searchObjectsInContext:@"PluPlu" Predicate:nil SortKey:@"ppCode" SortAscending:YES];    
}

#pragma mark -
#pragma mark XRmenu我的点单数据基本操作
//插入一份已点数据
+(void) insertNewDishOrder:(PluPlu*)item Error:(XRmenuError**)outError{
    NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    NSPredicate *pre1 = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"ddOrderId == '%@'",item.ppPluPluId]];
    NSMutableArray *exist = [self searchObjectsInContext:@"DishOrder" Predicate:pre1 SortKey:nil SortAscending:YES];
    NSString *errorMsg = [NSString  stringWithFormat:@"无法插入新的点菜数据(id=%@,name=%@)", item.ppPluPluId, JsonFiled(item.ppNames)];
    
    if ([exist count] > 0) {// 如果该菜品已经点了，则增加1份
        [self updateDishOrderNum:item.rsToDishOrder Increase:num(1) Error:outError];
    }
    else {//如果没有点，则插入一条新的点单记录
        NSEntityDescription *ent = [NSEntityDescription entityForName:@"DishOrder" inManagedObjectContext:MOC];
        DishOrder *oneOrder = [[DishOrder alloc] initWithEntity:ent insertIntoManagedObjectContext:MOC];
        //初始化以下9个字段
        oneOrder.ddCook=@"";
        oneOrder.ddNumber=num(1);
        oneOrder.ddName=JsonFiled(item.ppNames);
        oneOrder.ddPrice=item.ppPrice;
        oneOrder.ddCode=item.ppCode;
        oneOrder.ddUnit=JsonFiled(item.ppUnits);
        oneOrder.ddAmount=item.ppPrice;
        oneOrder.ddOrderId=item.ppPluPluId;
        oneOrder.ddOrderTime=[NSDate date];
        
        //建立与pluplu对象之间的联系
        oneOrder.rsToPluPlu=item;
        
        NSError *err1 = nil;
        if (![MOC save:&err1]) {//保存数据
            DebugLog(@"insertNewDishOrder error: %@", err1);
            NSDictionary *uDict = [NSDictionary dictionaryWithObject:errorMsg forKey:NSLocalizedDescriptionKey];
            XRmenuError *error1 = [XRmenuError errorWithDomain:kErrorDomain code:-22003 userInfo:uDict];
            if (error1) {
                *outError = error1;
            }else {
                abort();
            }
        }
        [oneOrder release];
    }
}
//更新菜品份数
+(void) updateDishOrderNum:(DishOrder*)item Increase:(NSNumber*)numb Error:(XRmenuError**)outError{
	NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
	NSPredicate *pre1 = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"ddOrderId == '%@'",item.ddOrderId]];
	NSMutableArray *exist = [self searchObjectsInContext:@"DishOrder" Predicate:pre1 SortKey:nil SortAscending:YES];
    NSString *errorMsg = [NSString  stringWithFormat:@"无法更新[我的点单]里更新指定菜品(id=%@,name=%@)的数量(num=%@)备注是%@", item.ddOrderId,item.ddName,numb, item.ddRemark];
	
	if ([exist count] == 1) {
		DishOrder *spitem = (DishOrder*)[exist objectAtIndex:0];
		float n = [spitem.ddNumber floatValue] + [numb floatValue];//计算出总的份数
		if (n <= 0) {//如果总份数小于等于0，则删除该份点单
			[self deleteOneDishOrder:item Error:outError];
		}
        else {
			spitem.ddNumber = num(n);//更新总份数
			spitem.ddAmount = num([spitem.ddNumber floatValue] * n);//更新总价格
			spitem.ddRemark = item.ddRemark; // 更新备注
			NSError *err1 = nil;
			if (![MOC save:&err1]) {//保存结果
				DebugLog(@"updateDishOrderNum error: %@", err1);
				NSDictionary *uDict = [NSDictionary dictionaryWithObject:errorMsg forKey:NSLocalizedDescriptionKey];
				XRmenuError *error1 = [XRmenuError errorWithDomain:kErrorDomain code:-22005 userInfo:uDict];
				if (error1) {
					*outError = error1;
				}else {
					abort();
				}
			}
		}
	}else {
		NSDictionary *uDict = [NSDictionary dictionaryWithObject:errorMsg forKey:NSLocalizedDescriptionKey];
		XRmenuError *error1 = [XRmenuError errorWithDomain:kErrorDomain code:-22004 userInfo:uDict];
		if (error1) {
			*outError = error1;
		}
	}
}
//删除所有已点菜品
+(void) deleteAllDishOrder:(XRmenuError**)outError{
	NSMutableArray *allDishOrders = [self searchObjectsInContext:@"DishOrder" Predicate:nil SortKey:nil SortAscending:YES];
//    NSString *errorMsg = @"无法清除所有已点单数据!";
    
	if ([allDishOrders count] > 0) {
		for (DishOrder *item in allDishOrders) {
            XRmenuError *err1 = nil;
            [self deleteOneDishOrder:item Error:&err1];   
            if (err1) {
				*outError = err1;
			}
        }
	}
}
//删除一份已点菜品
+(void) deleteOneDishOrder:(DishOrder*)item Error:(XRmenuError**)outError{
	NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
	NSPredicate *pre1 = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"ddOrderId == '%@'",item.ddOrderId]];
	NSMutableArray *exist = [self searchObjectsInContext:@"DishOrder" Predicate:pre1 SortKey:nil SortAscending:YES];
    NSString *errorMsg = [NSString stringWithFormat:@"无法删除指定的菜品数据(id=%@,name=%@)", item.ddOrderId,item.ddName];
    
	if ([exist count] == 1) {
        //删除双方的连接关系
        PluPlu *pluplu=item.rsToPluPlu;
        pluplu.rsToDishOrder=nil;
        [MOC deleteObject:item];
        
		NSError *err1 = nil;
		if (![MOC save:&err1]) {
			DebugLog(@"deleteOneDishOrder error: %@", err1);
			NSDictionary *uDict = [NSDictionary dictionaryWithObject:errorMsg forKey:NSLocalizedDescriptionKey];
			XRmenuError *error1 = [XRmenuError errorWithDomain:kErrorDomain code:-22007 userInfo:uDict];
			if (error1) {
				*outError = error1;
			}else {
				NSAssert(NO, errorMsg);
				abort();
			}
		}
	}else {
		NSDictionary *uDict = [NSDictionary dictionaryWithObject:errorMsg forKey:NSLocalizedDescriptionKey];
		XRmenuError *error1 = [XRmenuError errorWithDomain:kErrorDomain code:-22006 userInfo:uDict];
		if (error1) {
			*outError = error1;
		}
	}
}

#pragma mark -
#pragma mark XRmenu数据库操作基础方法
//清空数据库所有表的内容
+(BOOL) clearDBManagedObjectContext:(NSManagedObjectContext *)MOC{
	BOOL rtn = NO;
	
	[self deleteAllObjects:@"PluMenu" ManagedObjectContext:MOC] ;
	[self deleteAllObjects:@"PluSort" ManagedObjectContext:MOC];
	[self deleteAllObjects:@"PluPlu" ManagedObjectContext:MOC];
	[self deleteAllObjects:@"PluFood" ManagedObjectContext:MOC];
	[self deleteAllObjects:@"PluDrink" ManagedObjectContext:MOC];
	[self deleteAllObjects:@"PluCigarete" ManagedObjectContext:MOC];
	[self deleteAllObjects:@"PluPluTag" ManagedObjectContext:MOC];
	[self deleteAllObjects:@"PluSpecialSort" ManagedObjectContext:MOC];
    [self deleteAllObjects:@"PluSpecialCode" ManagedObjectContext:MOC];
	[self deleteAllObjects:@"DishOrder" ManagedObjectContext:MOC];
    [self deleteAllObjects:@"PluTable" ManagedObjectContext:MOC];
    
	NSError *error;
	
	if (![MOC save:&error]) {
		NSArray* detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey];
		if(detailedErrors != nil && [detailedErrors count] > 0) {
			for(NSError* detailedError in detailedErrors) {
				DebugLog(@"  DetailedError: %@", [detailedError userInfo]);
			}
		}
		else {
			DebugLog(@"  %@", [error userInfo]);
		}
		abort();
	}else {
		rtn = YES;
	}
	
	return rtn;
}

//删除一个数据表内容
+(void) deleteAllObjects: (NSString *) entityDescription ManagedObjectContext:(NSManagedObjectContext *)MOC {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityDescription inManagedObjectContext:MOC];
    [fetchRequest setEntity:entity];
	
    NSError *error;
    NSArray *items = [MOC executeFetchRequest:fetchRequest error:&error];
    [fetchRequest release];
	
	
    for (NSManagedObject *managedObject in items) {
        [MOC deleteObject:managedObject];
        DebugLog(@"%@ object deleted",entityDescription);
    }
    if (![MOC save:&error]) {
        DebugLog(@"Error deleting %@ - error:%@",entityDescription,error);
    }
}

//////////////////////////////////
//传入参数：没有查询条件，有MOC对象
+(NSMutableArray *) getObjectsMOC:(NSString*)entityName SortKey:(NSString*)sortKey SortAscending:(BOOL)sortAscending ManagedObjectContext:(NSManagedObjectContext *)managedObjectContext{
	return [self searchObjectsMOC:entityName Predicate:nil SortKey:sortKey SortAscending:sortAscending ManagedObjectContext:managedObjectContext];
}

//传入参数：有查询条件，有MOC对象
+(NSMutableArray *)searchObjectsMOC:(NSString*)entityName Predicate:(NSPredicate *)predicate SortKey:(NSString*)sortKey SortAscending:(BOOL)sortAscending ManagedObjectContext:(NSManagedObjectContext *)MOC{
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:MOC];
	[request setEntity:entity];	
	
	// If a predicate was passed, pass it to the query
	if(predicate != nil)
	{
		[request setPredicate:predicate];
	}
	
	// If a sort key was passed, use it for sorting.
	if(sortKey != nil)
	{
		NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:sortAscending];
		NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
		[request setSortDescriptors:sortDescriptors];
		[sortDescriptors release];
		[sortDescriptor release];
	}
	
	NSError *error=nil;
	
	NSMutableArray *mutableFetchResults = [[[MOC executeFetchRequest:request error:&error] mutableCopy] autorelease];
	
	[request release];
	if (error != nil){
		DebugLog(@"数据检索错误: %@", [error localizedDescription]);
	}
	return mutableFetchResults;
}

//////////////////////////////////
//传入参数：没有查询条件，没有MOC对象
+(NSMutableArray *) getObjectsFromContext:(NSString*)entityName SortKey:(NSString*)sortKey SortAscending:(BOOL)sortAscending{
	return [self searchObjectsInContext:entityName Predicate:nil SortKey:sortKey SortAscending:sortAscending];
}

//传入参数：有查询条件，没有MOC对象。对一个字段排序
+(NSMutableArray *)searchObjectsInContext:(NSString*)entityName Predicate:(NSPredicate *)predicate SortKey:(NSString*)sortKey SortAscending:(BOOL)sortAscending{
	NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:MOC];
	[request setEntity:entity];	
	
	// If a predicate was passed, pass it to the query
	if(predicate != nil)
	{
		[request setPredicate:predicate];
	}
	
	// If a sort key was passed, use it for sorting.
	if(sortKey != nil)
	{
		NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:sortAscending];
		NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
		[request setSortDescriptors:sortDescriptors];
		[sortDescriptors release];
		[sortDescriptor release];
	}
	
	NSError *error=nil;
	
	NSMutableArray *mutableFetchResults = [[[MOC executeFetchRequest:request error:&error] mutableCopy] autorelease];
	if (error != nil){
		DebugLog(@"数据检索错误: %@", [error localizedDescription]);
	}
	
	[request release];
	
	return mutableFetchResults;
}

//////////////////////////////////
//传入参数：有查询条件，没有MOC对象。对一组字段排序
+(NSMutableArray *)searchObjectsInContext:(NSString*)entityName Predicate:(NSPredicate *)predicate SortKeys:(NSArray*)sortKeys SortAscending:(BOOL)sortAscending{
	NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:MOC];
	[request setEntity:entity];	
	
	// If a predicate was passed, pass it to the query
	if(predicate != nil)
	{
		[request setPredicate:predicate];
	}
	
	// If a sort key was passed, use it for sorting.
	if(sortKeys != nil)
	{
		NSMutableArray *sortDescriptors = [NSMutableArray arrayWithCapacity:[sortKeys count]];
		for (NSInteger ii=0; ii<[sortKeys count]; ii++) {
			NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[sortKeys objectAtIndex:ii] ascending:sortAscending];
			[sortDescriptors addObject:sortDescriptor];
			[sortDescriptor release];
		}
		[request setSortDescriptors:sortDescriptors];
	}
	
	NSError *error=nil;
	
	NSMutableArray *mutableFetchResults = [[[MOC executeFetchRequest:request error:&error] mutableCopy] autorelease];
	if (error != nil){
		DebugLog(@"数据检索错误: %@", [error localizedDescription]);
	}
	
	[request release];
	
	return mutableFetchResults;
}

#pragma mark -
#pragma mark Catalogs相关操作(Old)
+(NSMutableArray*) getAllCatalogsByBookID:(NSString*)bkid
{
	NSString *cond = [NSString stringWithFormat:@"rsToMenu.mMenuId == '%@'", bkid];
	return [self searchObjectsInContext:@"Catalogs" Predicate:[NSPredicate predicateWithFormat:cond] SortKey:@"cID" SortAscending:YES];
}

+(NSMutableArray*) getAllTagsWithLanguage;
{
	NSString *cond = [NSString stringWithFormat:@"tLanguageEx == '%@'", APPSESSION.language];
	return [self searchObjectsInContext:@"ProductTag" Predicate:[NSPredicate predicateWithFormat:cond] SortKey:@"tTagId" SortAscending:YES];
}

#pragma mark -
#pragma mark 我的点单数据基本操作(Old)
//插入一份已点数据
+(void) insertNewOrderProduct:(Product*)item Error:(XRmenuError**)outError
{
	XRmenuError *error = nil;
	if ([APPSESSION.currentOrderNo isEqualToString:@"No Order"]) {
		NSMutableArray *allorders = [self searchObjectsInContext:@"SaleOrder" Predicate:nil SortKey:nil SortAscending:YES];
		if ([allorders count] > 0) {
			SaleOrder *sitem = (SaleOrder*)[allorders objectAtIndex:0];
			APPSESSION.currentOrderNo = sitem.sProductOrderId;
		}else {
			NSString *newO = [self createNewSaleOrder:&error];
			if (error == nil) {
				APPSESSION.currentOrderNo = newO;
			}else {
				if (error) {
					*outError = error;
				}
				return;
			}
		}
	}
	NSString* condition =	[NSString stringWithFormat:@"sProductOrderId == '%@'",APPSESSION.currentOrderNo];
	NSPredicate *tpre1 = [NSPredicate predicateWithFormat:condition];
	NSMutableArray *tmpOd = [self searchObjectsInContext:@"SaleOrder" Predicate:tpre1 SortKey:nil SortAscending:YES];
	if ([tmpOd count] == 1) {
		SaleOrder *oitem = (SaleOrder*)[tmpOd objectAtIndex:0];
		NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
	
		// 判断是否需要加记录
		NSString *con1 = [NSString stringWithFormat:@"rsToProduct.pProductId == '%@' AND rsToSaleOrder.sProductOrderId == '%@'",item.pProductId, APPSESSION.currentOrderNo];
		NSPredicate *pre1 = [NSPredicate predicateWithFormat:con1];
		NSMutableArray *exist = [self searchObjectsInContext:@"SaleOrderProduct" Predicate:pre1 SortKey:nil SortAscending:YES];
		if ([exist count] > 0) {
			[self updateProductNum:item Increase:num(1) Error:outError];
		}else {
			NSEntityDescription *ent = [NSEntityDescription entityForName:@"SaleOrderProduct" inManagedObjectContext:MOC];
			SaleOrderProduct *pitem = [[SaleOrderProduct alloc] initWithEntity:ent insertIntoManagedObjectContext:MOC];
			NSString *newID = [NSString stringWithUUID];
			pitem.sSaleOrderProductId = newID;
			pitem.sID = num(0);
			pitem.sAmount = num(1);
			pitem.sUnitPrice = item.pSalePrice;
			pitem.sPrice = item.pSalePrice;
			pitem.sBatchNo = num(APPSESSION.currentBatchNo);
			pitem.rsToProduct = item;
			
			[oitem addRsToSaleOrderProductObject:pitem];
			
			NSError *err1 = nil;
			if (![MOC save:&err1]) {
				DebugLog(@"Coredata error: %@", err1);
				NSString *errorMsg = [[NSString alloc] initWithFormat:@"%@",@"无法创建新的点单商品"];
				NSDictionary *uDict = [NSDictionary dictionaryWithObject:errorMsg forKey:NSLocalizedDescriptionKey];
				[errorMsg release];
				XRmenuError *error1 = [XRmenuError errorWithDomain:kErrorDomain code:-22003 userInfo:uDict];
				if (error1) {
					*outError = error1;
				}else {
					abort();
				}
			}
			[pitem release];
		}
	}else {
		NSString *errorMsg = [[NSString alloc] initWithFormat:@"%@",@"无法找到当前单号的主单数据"];
		NSDictionary *uDict = [NSDictionary dictionaryWithObject:errorMsg forKey:NSLocalizedDescriptionKey];
		[errorMsg release];
		XRmenuError *error1 = [XRmenuError errorWithDomain:kErrorDomain code:-22002 userInfo:uDict];
		if (error1) {
			*outError = error1;
		}
	}

}
//更新菜品份数
+(void) updateProductNum:(Product*)item Increase:(NSNumber*)numb Error:(XRmenuError**)outError
{
	NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
	NSString *con1 = [NSString stringWithFormat:@"rsToProduct.pProductId == '%@' AND rsToSaleOrder.sProductOrderId == '%@'",item.pProductId, APPSESSION.currentOrderNo];
	NSPredicate *pre1 = [NSPredicate predicateWithFormat:con1];
	NSMutableArray *exist = [self searchObjectsInContext:@"SaleOrderProduct" Predicate:pre1 SortKey:nil SortAscending:YES];
	if ([exist count] == 1) {
		SaleOrderProduct *spitem = (SaleOrderProduct*)[exist objectAtIndex:0];
		float n = [spitem.sAmount floatValue] + [numb floatValue];
		if (n <= 0) {
			[self clearProduct:item Error:outError];
		}else {
			spitem.sAmount = num(n);
			spitem.sPrice = num([spitem.sUnitPrice floatValue] * n);
			NSError *err1 = nil;
			if (![MOC save:&err1]) {
				DebugLog(@"Coredata error: %@", err1);
				NSString *errorMsg = [[NSString alloc] initWithFormat:@"%@(%@)",@"无法更新点单商品的数量", numb];
				NSDictionary *uDict = [NSDictionary dictionaryWithObject:errorMsg forKey:NSLocalizedDescriptionKey];
				[errorMsg release];
				XRmenuError *error1 = [XRmenuError errorWithDomain:kErrorDomain code:-22005 userInfo:uDict];
				if (error1) {
					*outError = error1;
				}else {
					abort();
				}
			}
		}

	}else {
		NSString *errorMsg = [[NSString alloc] initWithFormat:@"%@",@"无法更新点单商品的数量"];
		NSDictionary *uDict = [NSDictionary dictionaryWithObject:errorMsg forKey:NSLocalizedDescriptionKey];
		[errorMsg release];
		XRmenuError *error1 = [XRmenuError errorWithDomain:kErrorDomain code:-22004 userInfo:uDict];
		if (error1) {
			*outError = error1;
		}
	}
}
//删除所有已点菜品
+(void) clearAllSaleProduct:(NSString*)orderno Error:(XRmenuError**)outError
{
	NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];

	NSString *con1 = [NSString stringWithFormat:@"rsToSaleOrder.sProductOrderId = '%@'",orderno];
	NSPredicate *pre1 = [NSPredicate predicateWithFormat:con1];
	NSMutableArray *exist = [self searchObjectsInContext:@"SaleOrderProduct" Predicate:pre1 SortKey:nil SortAscending:YES];
	if ([exist count] > 0) {
		for (SaleOrderProduct *item in exist) {
			[MOC deleteObject:item];
		}
		NSError *err1 = nil;
		if (![MOC save:&err1]) {
			DebugLog(@"Coredata error: %@", err1);
			NSString *errorMsg = [[NSString alloc] initWithFormat:@"%@(%@)",@"无法清除指定单号的所有Product", orderno];
			NSDictionary *uDict = [NSDictionary dictionaryWithObject:errorMsg forKey:NSLocalizedDescriptionKey];
			[errorMsg release];
			XRmenuError *error1 = [XRmenuError errorWithDomain:kErrorDomain code:-22008 userInfo:uDict];
			if (error1) {
				*outError = error1;
			}else {
				NSAssert(NO, @"无法清除指定单号的所有Product");
				abort();
			}
		}
	}
}
//删除一份已点菜品
+(void) clearProduct:(Product*)item Error:(XRmenuError**)outError
{
	NSManagedObjectContext *MOC = [(XRmenu_HDAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
	NSString *con1 = [NSString stringWithFormat:@"rsToProduct.pProductId == '%@'",item.pProductId];
	NSPredicate *pre1 = [NSPredicate predicateWithFormat:con1];
	NSMutableArray *exist = [self searchObjectsInContext:@"SaleOrderProduct" Predicate:pre1 SortKey:nil SortAscending:YES];
	if ([exist count] == 1) {
		SaleOrderProduct *spitem = (SaleOrderProduct*)[exist objectAtIndex:0];
		
		[MOC deleteObject:spitem];
		NSError *err1 = nil;
		if (![MOC save:&err1]) {
			DebugLog(@"Coredata error: %@", err1);
			NSString *errorMsg = [[NSString alloc] initWithFormat:@"%@(%@)",@"无法清除指定的Product", item.pProductId];
			NSDictionary *uDict = [NSDictionary dictionaryWithObject:errorMsg forKey:NSLocalizedDescriptionKey];
			[errorMsg release];
			XRmenuError *error1 = [XRmenuError errorWithDomain:kErrorDomain code:-22007 userInfo:uDict];
			if (error1) {
				*outError = error1;
			}else {
				NSAssert(NO, @"无法清除指定的Product");
				abort();
			}
		}
	}else {
		NSString *errorMsg = [[NSString alloc] initWithFormat:@"%@(%@)",@"没有指定的Product需要清除", item.pProductId];
		NSDictionary *uDict = [NSDictionary dictionaryWithObject:errorMsg forKey:NSLocalizedDescriptionKey];
		[errorMsg release];
		XRmenuError *error1 = [XRmenuError errorWithDomain:kErrorDomain code:-22006 userInfo:uDict];
		if (error1) {
			*outError = error1;
		}
	}
}
//获取所有已点菜品
+(NSMutableArray*) getAllOrderedProduct
{
	return [self searchObjectsInContext:@"DishOrder" Predicate:nil SortKey:@"ddOrderTime" SortAscending:YES];
}

#pragma mark XRmenu菜品实时查询(XRmenu V2.0 提供!)
+(NSMutableArray*) searchByString:(NSString*)searchtxt
{
	if ([searchtxt length] <= 0) {
		return [self getObjectsFromContext:@"PluPlu" SortKey:@"ppCode" SortAscending:YES];
	}else {
		NSString *cond = [NSString stringWithFormat:@"pName CONTAINS [c] '%@' OR pSpellCode CONTAINS [c] '%@'", searchtxt, searchtxt];
		NSPredicate *pre = [NSPredicate predicateWithFormat:cond];
		return [self searchObjectsInContext:@"PluPlu" Predicate:pre SortKey:@"ppCode" SortAscending:YES];
	}
}
@end
